﻿using System.Collections.Generic;
using YooAsset;

namespace Client.Base
{
    public class FsmCreateDownloader : PatchState
    {
        private List<ResourceDownloaderOperation> downloaderOperations = new();

        public FsmCreateDownloader(PatchProcess procedure) : base(procedure)
        {
        }

        public override void OnEnter()
        {
            this.Log("[Patch] FsmCreateDownloader.");
            var packages = YAPackageInfo.Setting.packages;
            for (int i = 0; i < packages.Length; i++)
                CreateDownloader(packages[i].packageName);

            List<ResourceDownloaderOperation> mergeDownloaders = new();

            for (int i = 0; i < downloaderOperations.Count; i++)
            {
                if (downloaderOperations[i].TotalDownloadCount == 0)
                {
                    continue;
                }

                mergeDownloaders.Add(downloaderOperations[i]);
            }

            if (mergeDownloaders.Count == 0)  //资源最新，不需要更新
            {
                Process.TryTransition<FsmDownloadPackageOver>();
            }
            else
            {
                Process.SetDownloaders(mergeDownloaders);
                Process.TryTransition<FsmDownloadPackageFiles>();
            }
        }
        private void CreateDownloader(string packageName)
        {
            var package = YooAssets.GetPackage(packageName);
            var downloader = package.CreateResourceDownloader(10, 3);
            downloaderOperations.Add(downloader);

        }
    }
}

